<?php

namespace App\Http\Controllers\Admin\UserManager;

use App\Enums\UserEnum;
use App\Enums\RedisKeyEnum;
use App\Exceptions\BasicException;
use App\Services\Tools\RedisService;
use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;    //引用http请求类
use App\Response\Response;
use App\Services\Tools\FinancialService;
use Illuminate\Support\Facades\Validator;

class UserBankController extends BaseController {

    /**
     * @api {post} /user-manager/user-bank 支付宝账号-创建
     * @apiVersion 0.1.0
     * @apiName 会员管理-支付宝账号-创建
     * @apiGroup 会员管理
     *
     *
     * @apiParam {number} user_code                         编号
     * @apiParam {string} cardholder                       姓名
     * @apiParam {string} bank_num                         账号
     *
     * @apiSuccessExample 成功响应
     *
     *      {"code":200,"data":true}
     *
     * @apiError 10001 参数校验失败
     *
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     *
     */
    public function create(Request $request)
    {
        $v = app('validator')->make($request->all(),
            [
                'user_code' => 'required|numeric|exists:mysql.ln_user_data,user_code',
                'cardholder' => 'required|string',
                'bank_num' => 'required|string',
                'card_number' => 'required|string|size:18',
                'mobile' => 'required|integer|gt:0',
            ]
        );
        if ($v->fails()) throw new BasicException(10001, getValidateMessage($v->messages()));

        $params = $request->input();

        //查询用户信息
        $user = app('model_user_data')->select('user_id')->where('user_code', $params['user_code'])->first();
        if (empty($user)) throw new BasicException(0, '用户编号不存在');

//        $count = app("model_user_bank")->where([
//            ["user_id", "=" , $user->user_id],
//            ["bank_type", "=" , 1],
//            ["bank_num", "=" , $params['bank_num']],
//        ])->count();
//        if ($count > 0) {
//            throw new BasicException(10001, '账号已存在');
//        }

        //判断支付宝账号是否重复
        $bankInfo = app('model_user_bank')->where('bank_type', 1)->where('bank_num', $params['bank_num'])->where('is_deleted', 0)->first();
        if ($bankInfo) {
            throw new BasicException(0, "该支付宝账号已绑定");
        }
        $insert_data = [
            'user_id'     => $user['user_id'],
            'bank_num'    => $params['bank_num'],
            'cardholder'  => $params['cardholder'],
            'bank_type'   => 1,
            'bank_name'   => '支付宝',
            'add_time'    => time(),
            'update_time' => time(),
            'card_number' => $params['card_number'],
            'mobile'      => $params['mobile'],
            'check_status' => 4
        ];

        $res = app('repo_user');

        $rows = $res->addUserBank($insert_data);
        if ($rows){
            $switch = app('redis')->get(RedisKeyEnum::USER_ALIPAY_AUTOCHECK_SWITCH);
            if (!empty($switch)){
                $sw = json_decode($switch,true);
                if (isset($sw['status']) && $sw['status']==1){
                    //将用户支付宝信息发起校验
                    $userInfo = RedisService::getUserBaseInfo($user['user_id']);
                    $check = (new FinancialService())->syncCheckAliPayInfo([
                        'truename'  =>  $params['cardholder'],
                        'id_card'   =>  $params['card_number'],
                        'alipay_account'=>  $params['bank_num'],
                        'mobile'    =>  $params['mobile'],
                        'user_id'   =>  $user['user_id'],
                        'user_code' =>  $userInfo['user_code'],
                        'nickname'  =>  $userInfo['nickname'],
                    ]);
                } else {
                    app('model_user_bank')->where('id', $rows['id'])->update(['check_status' => 2]);
                }
            }
        }
        if (!$rows) {
            throw new BasicException(10001, "插入失败！");
        }

        return Response::sendData(true);
    }

    /**
     * @api {delete} /user-manager/user-bank 支付宝账号-删除
     * @apiVersion 0.1.0
     * @apiName 会员管理-支付宝账号-删除
     * @apiGroup 会员管理
     *
     * @apiParam {string} ids                       字符串分割的id 必传
     *
     * @apiSuccessExample 成功响应
     *
     *      {"code":200,"data":true}
     *
     * @apiError 10001 参数校验失败
     *
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     *
     */
    public function del(Request $request) {
        //参数校验
        try {
            $this->validate($request, [
                'ids' => 'required|string',
            ]);

        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }

        $idsStr = $request->input("ids");
        $idsArr = explode("," , $idsStr);

        $rows = app('repo_user')->delUserBank($idsArr);
        if (!$rows) {
            throw new BasicException(10001, "删除失败！");
        }

        return Response::sendData(true);
    }


    /**
     * @api {get} /user-manager/user-bank 支付宝账号-列表
     * @apiVersion 0.1.0
     * @apiName 会员管理-支付宝账号-列表
     * @apiGroup 会员管理
     *
     * @apiParam {string} cardholder 姓名 可选
     * @apiParam {string} bank_num 账号 可选
     * @apiParam {number} user_code 用户编号 可选
     * @apiParam {string} nickname 昵称 可选
     * @apiParam {number} page 当前页数 可选
     * @apiParam {number} perPage 分页容量 可选
     *
     *
     * @apiSuccessExample 成功响应
     *
     *
    {
    "code": 200,
    "data": {
        "list": [
            {
                "id": 1731,
                "bank_num(账号)": "6217002920000061805",
                "cardholder(姓名)": "姜琇",
                "add_time(添加时间)": "2020-04-18 15:59:42"
                "nickname(昵称)": "sn.白茶花",
                "user_code(用户id)": 605228
            }
        ],
        "meta": {
                "page": 1,
                "limit": 10,
                "next": null,
                "total": 1
            }
        }
     }
     *
     *
     */
    public function list(Request $request) {
        //参数校验
//        try {
            $validator= Validator::make($request->all(), [
                'perPage' => 'filled|numeric',
                'page' => 'filled|numeric',
            ]);
            if ($validator->fails()) {
                throw new BasicException(10001, $validator->errors()->first());
            }
//        } catch (\Exception $e) {
//            throw new BasicException(10001, json_encode($e->errors()));
//        }

        $list = app('repo_user')->getUserBankQueryList($request->input());

        return Response::sendList($list);
    }

    /**
     * @Desc:自动校验支付宝开关
     * @return string
     * @author: shiquan
     * @Time: 2022/9/29 20:43
     */
    public function autoCheckStatus() {
        $key = RedisKeyEnum::USER_ALIPAY_AUTOCHECK_SWITCH;
        if ($info = app('redis')->get($key)){
            $data = json_decode($info,true);
        } else {
            $data = [
                'status' => 0
            ];
            app('redis')->set($key, json_encode($data));
        }
        return Response::sendData($data);
    }

    /**
     * @Desc:更新自动校验支付宝开关
     * @return string
     * @author: shiquan
     * @Time: 2022/9/29 20:44
     */
    public function updateAutoCheckStatus(Request $request) {
        $param = $request->only('status');
        $validator= Validator::make($param, [
            'status' => 'required|integer|in:0,1',
        ]);
        if ($validator->fails()) {
            throw new BasicException(10001, $validator->errors()->first());
        }
        $key = RedisKeyEnum::USER_ALIPAY_AUTOCHECK_SWITCH;
        $data = [
            'status' => $param['status']
        ];
        app('redis')->set($key, json_encode($data));
        return Response::sendData($data);
    }
}
